package com.boboPlanet.filter;

import com.boboPlanet.comm.enums.GatewayConstance;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;

/**
 * @Description: TODO 约束：项目所有websocket地址默认以 /websocket结尾
 * @Author: mis_wu
 * @Date: 2023/7/27
 * @Company websocket
 **/
@Component
@Slf4j
public class WebsocketFilter implements GlobalFilter, Ordered {

    private static final String WEBSOCKET_SUFFIX = "/websocket";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("request into gateway webSocketFilter, current path is: {}", path);
        if (StringUtils.isNotBlank(path) && path.endsWith(WEBSOCKET_SUFFIX)){
            ServerHttpRequest build = request.mutate().headers(httpHeaders ->
                    httpHeaders.set(GatewayConstance.ALLOW_FILTER, String.valueOf(true))
            ).build();
            log.info("request into websocket filter");
            exchange.mutate().request(build);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
